package com.zh.obsdemo;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.obs.services.ObsClient;
import com.obs.services.model.*;
import com.zh.obsdemo.constant.HuaWeiConstants;
import com.zh.obsdemo.test.AKSK;
import com.zh.obsdemo.test.Constants;

import java.io.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

/**
 * @author :fjw
 * @description:TODO
 * @date :2020/10/8 11:39
 */
public class ObsDemo {
	public static void main(String[] args) throws NoSuchAlgorithmException, KeyManagementException, IOException {
		//获取临时ak/sk
		JSONObject aksk = AKSK.getAKSK();
		Map<String,String> credential = (Map) aksk.get("credential");
		String endPoint = HuaWeiConstants.OBS_ENDPOINT;
		String ak = credential.get("access");
		String sk = credential.get("secret");
		String securityToken = credential.get("securitytoken");//临时需要

		//使用临时ak/sk初始化OBS客户端
		ObsClient obsClient = new ObsClient(ak, sk, securityToken, endPoint);
		//使用永久ak/sk初始化OBS客户端
		//ObsClient obsClient1 = new ObsClient(ak, sk, endPoint);
		//使用访问obs
		//创建桶
		HeaderResponse response = obsClient.createBucket("bucketname");


		//上传对象
		obsClient.putObject("bucketname", "objectname", new ByteArrayInputStream("Hello OBS".getBytes()));

		//下载对象
		ObsObject obsObject = obsClient.getObject("bucketname", "objectname");
		InputStream content = obsObject.getObjectContent();
		if (content !=null) {
			BufferedReader reader = new BufferedReader(new InputStreamReader(content));
			while (true)
			{
				String line = reader.readLine();
				if (line == null)
					break;
				System.out.println("\n" + line);
			}
			reader.close();
			content.close();
		}

		//列举对象
		ObjectListing objectListing = obsClient.listObjects("bucketname");
		for(ObsObject obs : objectListing.getObjects()){
			System.out.println(" - " + obs.getObjectKey() + "  " +  "(size = " + obs.getMetadata().getContentLength() + ")");
		}

		//删除对象
		DeleteObjectResult result = obsClient.deleteObject("bucketname", "objectname");
		boolean deleteMarker = result.isDeleteMarker();
		//关闭obsclient
		obsClient.close();
	}
}
